﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using ZSZ.Core.Entities;
using ZSZ.EntityFramework;

namespace ZSZ.Application
{
    public class Repository<T>:IRepository<T> where T:BaseEntity 
    {
        private readonly ZSZDbContext _context = null;
        private readonly DbSet<T> _dbSet;

        public Repository(ZSZDbContext context)
        {
            _context = context;
            _dbSet = _context.Set<T>();
        }


        public void Insert(T entity)
        {
            _dbSet.Add(entity);
        }

        public void Update(T entity)
        {
            _dbSet.Attach(entity);
            _context.Entry(entity).State = EntityState.Modified;
        }

        public void SaveOrUpdate(T entity,bool isAdd)
        {
            if (isAdd)
            {
                Insert(entity);
            }
            else
            {
                Update(entity);
            }
        }

        public T Get(Expression<Func<T, bool>> predicate)
        {
            return _dbSet.AsNoTracking().FirstOrDefault(predicate);
        }

        public void Delete(T entity)
        {
            _dbSet.Remove(entity);
        }

        public T GetOneById(long id)
        {
            return _dbSet.AsNoTracking().FirstOrDefault(e => e.Id == id);
        }

        public IQueryable<T> GetAllDataEntity()
        {
            return _dbSet.AsNoTracking().Where(e => e.IsDeleted == false);
        }

        public void DeleteById(long id)
        {
            var data = GetOneById(id);
            data.IsDeleted = true;
            SaveOrUpdate(data,false);
        }
    }
}